package com.liuqi.iot.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.liuqi.common.exception.AppException;
import com.liuqi.iot.bean.dto.AlarmDefineDTO;
import com.liuqi.iot.bean.dto.AlarmDefinePublishedDTO;
import com.liuqi.iot.bean.dto.DeviceModelDTO;
import com.liuqi.iot.bean.query.AlarmDefineQuery;
import com.liuqi.iot.vo.AlarmDefineVO;
import com.liuqi.sys.common.ErrorCodes;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 报警规则定义
 *
 * @author  LiuQi 2025/3/25-9:09
 * @version V1.0
 **/
@Service
public class AlarmDefineService {
    @Autowired
    private AlarmDefineEntityService defineEntityService;

    @Autowired
    private AlarmDefinePublishedEntityService publishedEntityService;

    @Autowired
    private DeviceModelEntityService modelEntityService;

    /**
     * 报警规则定义下线
     */
    public void offline(String id) {
        AlarmDefineDTO defineDTO = defineEntityService.findById(id)
                .orElseThrow(AppException.supplier(ErrorCodes.IOT_ALARM_DEFINE_NOT_EXISTS));
        defineDTO.setStatus(3);
        defineEntityService.update(defineDTO);
        publishedEntityService.deletePhysical(id);
    }

    /**
     * 发布报警规则定义
     */
    public void publish(String id) {
        AlarmDefineDTO defineDTO = defineEntityService.findById(id)
                .orElseThrow(AppException.supplier(ErrorCodes.IOT_ALARM_DEFINE_NOT_EXISTS));
        defineDTO.setStatus(1);
        defineEntityService.update(defineDTO);
        publishedEntityService.deletePhysical(id);
        AlarmDefinePublishedDTO publishedDTO = new AlarmDefinePublishedDTO();
        BeanUtils.copyProperties(defineDTO, publishedDTO);
        publishedEntityService.insert(publishedDTO);
    }

    public IPage<AlarmDefineVO> pageQuery(AlarmDefineQuery query) {
        IPage<AlarmDefineDTO> page = defineEntityService.pageQuery(query);
        List<AlarmDefineDTO> list = page.getRecords();
        Map<String, String> modelNameMap = new HashMap<>(16);
        if (!CollectionUtils.isEmpty(list)) {
            // 补充模型名称
            List<String> modelIds = list.stream().map(AlarmDefineDTO::getModelId).toList();
            modelNameMap = modelEntityService.findByIds(modelIds)
                    .stream()
                    .collect(Collectors.toMap(DeviceModelDTO::getId, DeviceModelDTO::getName));
        }

        Map<String, String> pMap = modelNameMap;
        return page.convert(dto -> {
            AlarmDefineVO vo = new AlarmDefineVO();
            BeanUtils.copyProperties(dto, vo);
            vo.setModelName(pMap.get(dto.getModelId()));
            return vo;
        });
    }
}
